import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import "./index.less";
import CommonCpasTable from "../components/CommonCpasTable";
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { getSeekAuditReportTemplate, getjudgmentInit, gettableIsVerifyList, templateInitApi } from "./service";
import { history, useModel } from "umi";
import notify from "devextreme/ui/notify";
import Icon, { WarningOutlined } from "@ant-design/icons";
import PageLoading from "../components/PageLoading";
import { Tooltip } from "antd";
import FullNamePupop from "../components/CommonCpasTable/fullNamePupop";

const UnFinancialStatements = (props: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, zcbfid, bsdw } = initialState?.curPart as API.CurPart;
    const refsCommonCpasTableun = useRef<any>();
    const refFullNamePupop = useRef<any>();
    const [spinLoad, setSpinLoad] = useState<boolean>(false);
    const [spinAntTabs, setSpinAntTabs] = useState<boolean>(true);
    const [isInitBtn, setIsInitBtn] = useState<boolean>(true);
    const { pathname, query }: any = window.location || {};

    const [valIndex, setValIndex] = useState<string>('1');
    const [antTabsData, setAntTabsData] = useState<any[]>([
        {
            tabName: '资产',
            tabKey: '1',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '未审财务报表-资产表',
                titleName: '资产负债表',
                WscwbbType: '资产类',
                origin: '未审财务报表',
                tabsIndex: 1,
            }
        },
        {
            tabName: '负债',
            tabKey: '2',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '未审财务报表-负债表',
                titleName: '资产负债表（续）',
                WscwbbType: '负债类',
                origin: '未审财务报表',
                tabsIndex: 2,
            }
        },
        {
            tabName: '利润',
            tabKey: '3',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '未审财务报表-利润表',
                titleName: '利润表',
                WscwbbType: '利润类',
                origin: '未审财务报表',
                tabsIndex: 3,
            }
        },
        {
            tabName: '现流',
            tabKey: '4',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '未审财务报表-现金流量表',
                titleName: '现金流量表',
                WscwbbType: '现金流量类',
                origin: '未审财务报表',
                tabsIndex: 4,
            }
        },
        {
            tabName: '现流附',
            tabKey: '5',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '未审财务报表-现金流补充资料表',
                titleName: '现金流量表补充资料',
                WscwbbType: '现金流补充资料类',
                origin: '未审财务报表',
                tabsIndex: 5,
            }
        },

    ]);
    const tableNameGroup = ['未审财务报表-资产表', '未审财务报表-负债表', '未审财务报表-利润表', '未审财务报表-现金流量表', '未审财务报表-现金流补充资料表'];
    const changeTabsKey = (val: string) => {
        setValIndex(val);
        history.push('/ReportSys/UnFinancialSys/unFinancialStatements');

    };
    const changeTabs = (changeCur: string) => {
        antTabsData.forEach(item => {
            if (item.propsData.tableName === changeCur) {
                setValIndex(item.tabKey);
            }
        });
    }

    const antTabsDetail = async () => {
        const res = await gettableIsVerifyList({ tableName: "未审财务报表", dbname, isTid: false });
        if (res.success) {
            if (res.data?.length) {
                const tempsName = res.data.map((item: { name: string }) => item.name).join(',') || "";
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        const msg = item.propsData.tableName;
                        const isName = tempsName.includes(msg);
                        item.isVerify = isName;
                        return item;
                    });
                    return newData;
                });
            } else {
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        item.isVerify = false;
                        return item;
                    });
                    return newData;
                });
            }
        } else {
            notify(`获取isVerify校验失败！`, "error", 2000);
        }
    }
    const getAuditReportTemplate = async (yearTableName: any) => {
        try {
            const judg = await getjudgmentInit({
                dbname,
                type: 'fs',
                tableRealName: yearTableName
            });

            if (judg.success) {
                if (judg.data.count_number === 0) {
                    setSpinLoad(true);
                    const res = await getSeekAuditReportTemplate({
                        zcbfid
                    });
                    if (res.success) {
                        const resTemp: any = await templateInitApi({
                            dbName: dbname,
                            templateName: res.data.AuditReportTemplate,
                            tableNames: tableNameGroup,
                            type: 'fs',
                        });
                        setSpinLoad(false);
                        if (resTemp.success) {
                            notify(`模板初始化成功`, "success", 2000);
                            if (!refsCommonCpasTableun.current) return;
                            await refsCommonCpasTableun.current.CPASInit2(yearTableName, true);
                            await antTabsDetail();
                        } else {
                            if (res.data.AuditReportTemplate) {
                                notify(`${resTemp.msg}`, "error", 2000);
                            } else {
                                notify(`请在首页组成部分信息内选择报告模板`, "warning", 2000);
                            }
                        }
                    }
                } else {
                    if (!refsCommonCpasTableun.current) return;
                    await refsCommonCpasTableun.current.CPASInit2(yearTableName, false);
                    await antTabsDetail();
                }
                setIsInitBtn(false);
            } else {
                notify(`获取判断是否初始化失败！`, "error", 2000);
            }
        } catch (error) {
            notify(`获取判断是否初始化失败！`, "error", 2000);
        }
    };

    const excelInfo = [
        {
            cpastableParam: {
                tname: "未审财务报表-资产表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "资产负债表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "未审财务报表-负债表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "资产负债表（续）",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "未审财务报表-利润表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "利润表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "未审财务报表-现金流量表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "现金流量表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "未审财务报表-现金流补充资料表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "现金流量表补充资料",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: false
        },
    ]

    const changeSpinAntTabs = async (newData: boolean, yearTableName: any) => {
        setSpinAntTabs(newData);
        setIsInitBtn(false); /* setIsInitBtn(false); 这个状态很重要; 请勿删除！ 20230727 */
        setValIndex('1');
        if (newData && refsCommonCpasTableun.current) {
            refsCommonCpasTableun.current.CPASInit2("未审财务报表-资产表", false);
        }
    }

    useEffect(() => {
        getAuditReportTemplate("未审财务报表-资产表");
    }, []);

    useEffect(() => {
        if (pathname === '/ReportSys/UnFinancialSys/unFinancialStatements' && query.tableName) {
            changeTabs(query.tableName);
        }
    }, [pathname, query]);

    return <>
        <div className="UnFinancialStatements_whole">
            {/* <Button
                type='default'
                className="defaultBtn"
                onClick={() => {
                    getAuditReportTemplate();
                }}
                text='初始化'
            /> */}
            <PageLoading
                isOpen={spinLoad}
                isMaskClose={false}
                content={"正在初始化 ..."}
                width={200}
            />
            {spinAntTabs && <AntTabs defaultActiveKey="1"
                className="changeTabsHeight"
                destroyInactiveTabPane={true}
                onChange={(val: string) => { changeTabsKey(val); }} activeKey={valIndex}>
                {
                    antTabsData.map((item: any) => (
                        <AntTabs.TabPane
                            destroyInactiveTabPane={true}
                            tab={
                                // <Tooltip placement="topLeft" title={item.propsData.titleName}>  </Tooltip>
                                // <div onDoubleClick={() => handleDoubleClick(item.propsData.tableName, item.tabName)}>
                                <div>
                                    <span>{item.tabName}
                                        {item.isVerify && <span className="render-span"
                                            onClick={(e) => {
                                                if (refsCommonCpasTableun.current) {
                                                    refsCommonCpasTableun.current.CPASOpenDetail();
                                                }
                                            }}>
                                            <WarningOutlined />
                                        </span>}
                                    </span>
                                </div>

                            }
                            key={item.tabKey}
                            closable={item.closable}
                        >
                            <CommonCpasTable CPASTableProps={item.propsData} CPASTableTabName={item.tabName}
                                isInitBtn={isInitBtn}
                                changeIsInitBtn={() => {
                                    setIsInitBtn(false);
                                }}
                                biaoAllData={antTabsData}
                                cpasChangeSpinAntTabs={(data: boolean, yearTableName: any) => { changeSpinAntTabs(data, yearTableName) }} antTabsTabPaneDetail2={() => antTabsDetail()}
                                excelParams={excelInfo} tableNameGroup={tableNameGroup} ref={refsCommonCpasTableun} commonCpasTableDisplay={"commonCpasTableDisplay"} />
                        </AntTabs.TabPane>
                    ))
                }
            </AntTabs>}

            <FullNamePupop ref={refFullNamePupop} />
        </div>
    </>
}
export default UnFinancialStatements;
